<template>
  <div class="quality-inspection-container"> 
    <!-- 质检记录列表 -->
    <el-table :data="qualityRecords" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column fixed type="index" label="序号" width="60" />
      <el-table-column prop="inspectionNumber" label="质检编号" width="150" />
      <el-table-column prop="produceCode" label="生产工单编号" width="150" />
      <el-table-column prop="produceName" label="生产工单名称" width="180" />
      <el-table-column prop="materialGroupName" label="物料群组名称" width="180" />
      <el-table-column prop="inspectedQuantity" label="检验数量" width="120" />
      <el-table-column prop="qualifiedQuantity" label="合格数量" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.qualifiedQuantity < scope.row.inspectedQuantity ? 'orange' : 'green' }">
            {{ scope.row.qualifiedQuantity }}
          </span>
        </template>
      </el-table-column>
      <!-- 合格百分比列，带进度条 -->
      <el-table-column label="合格百分比" width="200">
        <template #default="scope">
          <div class="percentage-container">
            <div 
              class="percentage-bar" 
              :style="{ 
                width: scope.row.qualifiedPercentage + '%',
                backgroundColor: getPercentageColor(scope.row.qualifiedPercentage)
              }"
            >
              {{ scope.row.qualifiedPercentage.toFixed(1) }}%
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="unqualifiedQuantity" label="不合格数量" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.unqualifiedQuantity > 0 ? 'red' : 'green' }">
            {{ scope.row.unqualifiedQuantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="inspector" label="质检人员" width="180" />
      <el-table-column prop="inspectionTime" label="质检时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.inspectionTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="200">
        <template v-slot="scope">
          <el-button link type="warning" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑质检记录弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑质检记录" width="600px">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px">
        <el-form-item label="质检编号" prop="inspectionNumber">
          <el-input v-model="editForm.inspectionNumber" disabled placeholder="质检编号（自动生成）" />
        </el-form-item>
        <el-form-item label="生产工单编号" prop="produceCode">
          <el-input v-model="editForm.produceCode" disabled />
        </el-form-item>
        <el-form-item label="生产工单名称" prop="produceName">
          <el-input v-model="editForm.produceName" disabled />
        </el-form-item>
        <el-form-item label="物料群组名称" prop="materialGroupName">
          <el-input v-model="editForm.materialGroupName" disabled />
        </el-form-item>
        <el-form-item label="检验数量" prop="inspectedQuantity">
          <el-input v-model.number="editForm.inspectedQuantity" placeholder="请输入检验数量" />
        </el-form-item>
        <el-form-item label="合格数量" prop="qualifiedQuantity">
          <el-input v-model.number="editForm.qualifiedQuantity" placeholder="请输入合格数量" />
          <div class="el-form-item__help">提示：合格数量必须在0到{{ editForm.inspectedQuantity }}之间</div>
        </el-form-item>
        <!-- 编辑弹窗中显示合格百分比 -->
        <el-form-item label="合格百分比">
          <div class="percentage-container" style="margin-top: 5px;">
            <div 
              class="percentage-bar" 
              :style="{ 
                width: editForm.qualifiedPercentage + '%',
                backgroundColor: getPercentageColor(editForm.qualifiedPercentage)
              }"
            >
              {{ editForm.qualifiedPercentage ? editForm.qualifiedPercentage.toFixed(1) + '%' : '0%' }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="不合格数量" prop="unqualifiedQuantity">
          <el-input v-model.number="editForm.unqualifiedQuantity" placeholder="请输入不合格数量" disabled />
        </el-form-item>
        <el-form-item label="质检人员" prop="inspector">
          <el-input v-model="editForm.inspector" placeholder="请输入质检人员" />
        </el-form-item>
        <el-form-item label="质检时间" prop="inspectionTime">
          <el-date-picker
            v-model="editForm.inspectionTime"
            type="datetime"
            placeholder="请选择质检时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watchEffect } from 'vue';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:5046';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

const pinia = useCounterStore();
const qualityRecords = ref<any[]>([]);
const selectedIds = ref<number[]>([]); // 用于批量删除的选中ID集合

// 分页参数（匹配新API的Index/Size）
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 查询表单
const searchForm = reactive({
  id: undefined,
  productionOrderId: undefined,
  materialGroupId: undefined,
});

// 弹窗控制
const editDialogVisible = ref(false);

// 编辑表单数据（匹配新API返回字段）
const editForm = reactive<any>({
  id: undefined,
  inspectionNumber: '',
  produceCode: '',
  produceName: '',
  materialGroupName: '',
  inspectedQuantity: undefined,
  qualifiedQuantity: undefined,
  qualifiedPercentage: 0, // 新增：合格百分比
  unqualifiedQuantity: undefined,
  inspector: '',
  inspectionTime: undefined,
  productionOrderId: undefined, // 后端需要的关联ID（不显示）
  materialGroupId: undefined,   // 后端需要的关联ID（不显示）
});

// 编辑表单验证规则
const editRules = reactive<FormRules>({
  inspectedQuantity: [
    { required: true, message: '请输入检验数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '检验数量不能小于1', trigger: 'blur' }
  ],
  qualifiedQuantity: [
    { required: true, message: '请输入合格数量', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value < 0 || value > editForm.inspectedQuantity) {
          callback(new Error(`合格数量必须在0到${editForm.inspectedQuantity}之间`));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  inspector: [{ required: true, message: '请输入质检人员', trigger: 'blur' }],
  inspectionTime: [{ required: true, message: '请选择质检时间', trigger: 'change' }],
});

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 根据百分比获取进度条颜色
const getPercentageColor = (percentage: number) => {
  if (percentage >= 90) return '#4CAF50'; // 绿色 - 优秀
  if (percentage >= 70) return '#8BC34A'; // 浅绿色 - 良好
  if (percentage >= 50) return '#FFC107'; // 黄色 - 一般
  return '#FF5252'; // 红色 - 较差
};

// 监听合格数量和检验数量变化，自动计算不合格数量和合格百分比
watchEffect(() => {
  if (editForm.inspectedQuantity && editForm.inspectedQuantity > 0 && editForm.qualifiedQuantity !== undefined) {
    // 计算不合格数量
    editForm.unqualifiedQuantity = editForm.inspectedQuantity - editForm.qualifiedQuantity;
    // 计算合格百分比
    editForm.qualifiedPercentage = (editForm.qualifiedQuantity / editForm.inspectedQuantity) * 100;
  }
});

// 获取质检记录列表（使用新API：QualityInspectionQuery）
const getQualityRecords = async () => {
  try {
    const response = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
      params: {
        // 新API参数：Index（页码）、Size（页大小）
        Index: pagination.currentPage,
        Size: pagination.pageSize,
        // 查询条件
        id: searchForm.id,
        productionOrderId: searchForm.productionOrderId,
        materialGroupId: searchForm.materialGroupId,
      },
    });

    if (response.data.code === 200 && response.data.data) {
      // 计算每条记录的合格百分比
      const records = response.data.data.totalPage || [];
      qualityRecords.value = records.map((record: any) => {
        return {
          ...record,
          qualifiedPercentage: record.inspectedQuantity 
            ? (record.qualifiedQuantity / record.inspectedQuantity) * 100 
            : 0
        };
      });
      pagination.total = response.data.data.totalcount || 0;
    } else {
      ElMessage.error(`获取质检记录失败: ${response.data.message || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error('网络异常，获取质检记录失败');
    console.error('Get quality records error:', error);
  }
};

// 打开编辑弹窗（回显新API返回的字段）
const openEditDialog = (row: any) => {
  editForm.id = row.id;
  editForm.inspectionNumber = row.inspectionNumber;
  editForm.produceCode = row.produceCode;
  editForm.produceName = row.produceName;
  editForm.materialGroupName = row.materialGroupName;
  editForm.inspectedQuantity = row.inspectedQuantity;
  editForm.qualifiedQuantity = row.qualifiedQuantity;
  editForm.unqualifiedQuantity = row.unqualifiedQuantity;
  // 计算合格百分比
  editForm.qualifiedPercentage = row.inspectedQuantity 
    ? (row.qualifiedQuantity / row.inspectedQuantity) * 100 
    : 0;
  editForm.inspector = row.inspector;
  editForm.inspectionTime = row.inspectionTime;
  editForm.productionOrderId = row.productionOrderId; // 保留后端关联ID
  editForm.materialGroupId = row.materialGroupId;     // 保留后端关联ID

  editDialogVisible.value = true;
};

// 提交编辑表单
const editFormRef = ref<FormInstance>();
const submitEditForm = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 编辑接口可根据后端实际地址调整，此处沿用原编辑接口（需确保字段匹配）
        const response = await axios.put('/api/QualityInspection/UpdateQualityInspection', {
          id: editForm.id,
          productionOrderId: editForm.productionOrderId,
          materialGroupId: editForm.materialGroupId,
          inspectedQuantity: editForm.inspectedQuantity,
          qualifiedQuantity: editForm.qualifiedQuantity,
          unqualifiedQuantity: editForm.unqualifiedQuantity,
          inspector: editForm.inspector,
          inspectionTime: editForm.inspectionTime,
        });

        if (response.data.code === 200) {
          ElMessage.success('编辑质检记录成功');
          editDialogVisible.value = false;
          getQualityRecords(); // 刷新列表
        } else {
          ElMessage.error(`编辑质检记录失败: ${response.data.message || '未知错误'}`);
        }
      } catch (error) {
        ElMessage.error('网络异常，编辑质检记录失败');
        console.error('Edit quality record error:', error);
      }
    }
  });
};

// 单条删除质检记录
const handleDelete = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除该质检记录吗？删除后数据将无法恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.delete('/api/QualityInspection/DeleteQualityInspection', {
        params: { id }
      });

      if (response.data.code === 200) {
        ElMessage.success('删除质检记录成功');
        getQualityRecords(); // 刷新列表
      } else {
        ElMessage.error(`删除质检记录失败: ${response.data.message || '未知错误'}`);
      }
    } catch (error) {
      ElMessage.error('网络异常，删除质检记录失败');
      console.error('Delete quality record error:', error);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 处理表格行选择（批量删除备用）
const handleSelectionChange = (val: any[]) => {
  selectedIds.value = val.map(item => item.id);
};

// 重置查询条件
const resetSearch = () => {
  searchForm.id = undefined;
  searchForm.productionOrderId = undefined;
  searchForm.materialGroupId = undefined;
  pagination.currentPage = 1; // 重置页码
  getQualityRecords(); // 刷新列表
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  getQualityRecords();
};

// 页码变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  getQualityRecords();
};

// 页面加载时只加载列表数据（无弹窗）
onMounted(() => {
  getQualityRecords();
});
</script>

<style scoped>
.quality-inspection-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}
.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.el-table {
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.el-pagination {
  margin-top: 15px;
  text-align: right;
}

/* 百分比进度条样式 */
.percentage-container {
  width: 100%;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

.percentage-bar {
  height: 100%;
  transition: width 0.3s ease;
  border-radius: 12px;
  color: white;
  text-align: center;
  line-height: 24px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  padding: 0 5px;
  box-sizing: border-box;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  .search-form .el-form-item {
    flex: 1 1 calc(50% - 20px);
    min-width: 200px;
  }
}
@media (max-width: 768px) {
  .quality-inspection-container {
    padding: 10px;
  }
  .search-form .el-form-item {
    flex: 1 1 100%;
  }
  .el-pagination {
    text-align: center;
  }
}
</style>
